package com.tfswx.jkgl.core.utils;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {

    /**
     * 转换集合map的key为小写
     *
     * @param orgList 原集合
     * @return 小写key集合
     */
    public static List<Map<String, String>> transformList(List<Map<String, String>> orgList) {
        List<Map<String, String>> result = Lists.newArrayList();
        orgList.forEach(row -> result.add(transformUpperCase(row, false)));
        return result;
    }

    /**
     * Map的key转小写
     *
     * @param orgMap 原集合
     * @return 小写key集合
     */
    public static Map<String, String> transformUpperCase(Map<String, String> orgMap, boolean replaceSymbol) {
        Map<String, String> resultMap = Maps.newHashMap();

        if (orgMap == null || orgMap.isEmpty()) {
            return resultMap;
        }

        Set<String> keySet = orgMap.keySet();
        for (String key : keySet) {
            String newKey = key.toLowerCase();
            if (replaceSymbol) {
                newKey = newKey.replace("_", "");
            }
            resultMap.put(newKey, orgMap.get(key));
        }

        return resultMap;
    }

    /**
     * 根据传入的regSymbol找到sql中特殊字符开头的参数字段
     *
     * @param regSymbol     要查询的标识符（正则写法，如：@|\$）
     * @param sql           sql语句
     * @param replaceSymbol 是否将匹配到的标识符去掉
     * @return 参数集合
     */
    public static List<String> matchSymbolFromSql(String regSymbol, String sql, boolean replaceSymbol) {
        if (org.apache.commons.lang3.StringUtils.isAnyBlank(regSymbol, sql)) {
            return Collections.emptyList();
        }
        List<String> result = Lists.newArrayList();
        String regTmp = StrUtil.format("({})((?!#)\\w*)", regSymbol);
        Pattern pattern = Pattern.compile(regTmp);
        Matcher matcher = pattern.matcher(sql);
        while (matcher.find()) {
            String value = matcher.group();
            if (replaceSymbol) {
                value = value.replaceFirst(regSymbol, "");
            }
            result.add(value);
        }
        return result;
    }

    public static String replace(String sql, Map<String, Object> param) {
        List<Integer> startIdxList = new ArrayList<>();
        for (int i = 0; i < sql.length(); i++) {
            if ('@' == sql.charAt(i)) {
                startIdxList.add(i);
            }
        }

        String value;
        for (int i = startIdxList.size() - 1; i >= 0; i--) {
            Integer startIdex = startIdxList.get(i);
            int endIndex = getEndIndex(sql, startIdex);
            String str1 = sql.substring(0, startIdex);
            String fn = sql.substring(startIdex + 1, endIndex);


            Object item = param.getOrDefault(fn, null);

            if (item == null) {
                value = null;
            } else if (item instanceof String) {
                value = StrUtil.format("'{}'", ((String) item).replace("'", "''"));
            } else {
                value = StrUtil.format("{}", item);
            }

            String str3 = sql.substring(endIndex);
            sql = str1 + value + str3;
        }
        return sql;
    }

    private static int getEndIndex(String str, int start) {
        for (int i = start + 1; i < str.length(); i++) {
            char c = str.charAt(i);
            if (!('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z')) {
                return i;
            }
        }
        return str.length();
    }
}
